<template>
  <div class="chat-container" :class="{ 'mobile-view': isMobile,'professional-mode': settingsStore.isProfessionalMode }">
    <div class="chat-header fixed-header"
    :style="{ 
    backgroundColor: 
      selectedModel.type === 'kingsha' 
        ? '#003bf4' 
        : (selectedModel.type === 'project' 
            ? '#f4ba40' 
            : '#ffffff')
  }"
    >
      <!-- <h1>AI Chat</h1> -->
       <!-- 新增模型选择下拉框 -->
       <div class="model-container">
       <div class="model-selector">
        
        <el-select 
          v-model="selectedModel"
          @change="saveModelSelection"
          class="w-48"
        >
          <el-option
            v-for="model in modelOptions"
            :key="model.value"
            :label="model.label"
            :value="model"
          />
        </el-select>
        </div>
      </div>
    </div>


    <div class="messages-container" ref="messagesContainer">
      <template v-if="messages.length">
        <ChatMessage
          v-for="message in messages"
          :key="message.id"
          :message="message"
          @update="handleMessageUpdate"
          @delete="handleMessageDelete"
          @regenerate="handleRegenerate"
        />
      </template>
      <div v-else class="empty-state">
        <el-empty description="开始对话吧" />
      </div>
    </div>

    <ChatInput :loading="isLoading" @send="handleSend" @clear="handleClear" :button-color="currentButtonColor" />
    <SettingsPanel v-model="showSettings" />
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue';
import { Setting } from '@element-plus/icons-vue';
import { useChatStore } from '../stores/chat';
import { chatApi } from '../utils/api';
import { messageHandler } from '../utils/messageHandler';
import ChatMessage from '../components/ChatMessage.vue';
import ChatInput from '../components/ChatInput.vue';
import SettingsPanel from '../components/SettingsPanel.vue';
import { useSettingsStore } from '../stores/settings';
import { ElMessage } from 'element-plus';
import { onMounted } from 'vue';
import { renderMarkdown } from '@/utils/markdown';
import { modelOptions } from '../stores/settings'; // 新增：直接导入模型选项

const isMobile = ref(/MicroMessenger/i.test(navigator.userAgent));

const chatStore = useChatStore();
const messages = computed(() => chatStore.messages);
const isLoading = computed(() => chatStore.isLoading);
const showSettings = ref(false);
const messagesContainer = ref(null);
const tableData = ref([]); 

onMounted(() => {
  // 确保 selectedModel 有默认值
  if (!selectedModel.value ) {
    selectedModel.value = modelOptions[0]; // 强制设置默认模型
  }
});

// const handleModelSelect = (modelValue) => {
//   // 手动设置选中的模型值
//   selectedModel.value = modelValue;
//   // 调用保存模型的方法
//   saveModelSelection();
// };


onMounted(async () => {
  try {
    const data = await chatApi.getHistoricalConversations();
    tableData.value = data;
  } catch (error) {
    // 保留模拟数据作为回退方案
    tableData.value = [
      {
        date: '2023-09-01',
        name: '会话一',
        value: '1200',
        detailContent: "[reasoning]### 思考过程\n- <font size=2>正在检查任务时效性</font>\n- <font size=2>时效性结果: 需及时回复</font>\n- <font size=2>正在给问题进行系统分类</font>\n- <font size=2>系统分类结果: 其他</font>\n[/reasoning]\n[inference]### Python实现冒泡排序\n\n```python\ndef bubble_sort(arr):\n    n = len(arr)\n    for i in range(n):\n        for j in range(0, n-i-1):\n            if arr[j] > arr[j+1]:\n                arr[j], arr[j+1] = arr[j+1], arr[j]\n    return arr\n```\n\n### 步骤\n1. **遍历数组**：从第一个元素到最后一个元素。\n2. **比较相邻元素**：如果前一个元素大于后一个元素，交换它们。\n3. **重复步骤**：直到没有元素需要交换。[/inference]" 
      }
    ]
  }
})



// 详情弹窗状态
const isDetailVisible = ref(false);
const currentDetail = ref('');

const showDetail = (item) => {
  // 新增渲染步骤
  const cleanedContent = item.detailContent.replace(
    /\[reasoning\]|\[\/reasoning\]|\[inference\]|\[\/inference\]/g,
    ''
  );
  const renderedContent = renderMarkdown(cleanedContent);
  currentDetail.value = renderedContent;
  isDetailVisible.value = true;
};

// 关闭详情弹窗
const closeDetail = () => {
  isDetailVisible.value = false;
};




// 监听消息变化，滚动到底部
watch(messages, () => {
  nextTick(() => {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  });
}, { deep: true });

// 发送消息时先添加思考中的消息
const handleSend = async (content, params = {}) => {
  console.log('handleSend:', params);
  chatStore.addMessage(messageHandler.formatMessage('user', content));
  // 创建思考中的AI消息
  const assistantMessage = messageHandler.formatMessage('assistant', '', true);
  chatStore.addMessage(assistantMessage);
  chatStore.isLoading = true;
  let success = false; // 标记操作是否成功完成

  try {
    const settingsStore = useSettingsStore();
    const messagesToSend = messages.value.slice(0, -1).map(m => ({
      role: m.role,
      content: m.content
    }));

    // 新增：将params附加到payload中
    const payload = new FormData();
    payload.append('query',content);
    if (params.is_records) {
      payload.append('is_records', params.is_records); // 根据接口需求调整参数名
    }

    // const response = await chatApi.sendMessage(payload, settingsStore.streamResponse);
    const response = await chatApi.sendMessage(payload, true);
    console.log('Response_Chatview:', response);

    if (settingsStore.streamResponse) {
      await messageHandler.processStreamResponse(response, {
        updateMessage: (updates) => chatStore.updateLastMessage(updates), // 实时更新
        updateTokenCount: (usage) => chatStore.updateTokenCount(usage)
      });
    }
    else {

    
    const cleanedContent = response.content.replace(/\n+/g, '\n') // 合并连续换行符
    const reasoning = response.reasoning

    await messageHandler.simulateStreamResponse(cleanedContent, reasoning, {
        // updateMessage: (updates) => chatStore.updateLastMessage(updates),
        updateMessage: (updates) => {
      // 显式传递reasoning到store
      chatStore.updateLastMessage({ 
        content: updates.content || '', 
        reasoning: updates.reasoning || reasoning,
        loading: updates.loading || true
      });
    },
        duration: 50 // 每个字符显示间隔（毫秒）
      });
    chatStore.updateTokenCount(response.usage);
  }
  success = true; // 操作成功
}
catch(error){
    // 清理未完成的AI消息
    chatStore.messages.pop();
  } finally {
  chatStore.isLoading = false;
}
};


// const handleSend = async (content, params = {}) => {
//   console.log('handleSend:', params);
//   chatStore.addMessage(messageHandler.formatMessage('user', content));
//   // 创建思考中的AI消息
//   const assistantMessage = messageHandler.formatMessage('assistant', '', true);
//   chatStore.addMessage(assistantMessage);
//   chatStore.isLoading = true;

//   try {
//     const settingsStore = useSettingsStore();
//     const messagesToSend = messages.value.slice(0, -1).map(m => ({
//       role: m.role,
//       content: m.content
//     }));

//     // 构建请求体
//     const payload = new FormData();
//     payload.append('query', content);
//     if (params.is_records) {
//       payload.append('is_records', params.is_records); // 根据接口需求调整参数名
//     }

//     // 调用API发送消息
//     const response = await chatApi.sendMessage(payload, settingsStore.streamResponse);
//     console.log('Response_Chatview:', response);

//     // 处理流式响应
//     console.log("settingsStore.streamResponse",settingsStore.streamResponse)
//     if (settingsStore.streamResponse) {
//       await messageHandler.processStreamResponse(response, {
//         updateMessage: (updates) => chatStore.updateLastMessage(updates),
//         updateTokenCount: (usage) => chatStore.updateTokenCount(usage)
//       });
//     } else {
//       // 非流式响应处理
//       const cleanedContent = response.content.replace(/\n+/g, '\n');
//       const reasoning = response.reasoning;
//       await messageHandler.simulateStreamResponse(cleanedContent, reasoning, {
//         updateMessage: (updates) => {
//           chatStore.updateLastMessage({
//             content: updates.content || '',
//             reasoning: updates.reasoning || reasoning,
//             loading: updates.loading || true
//           });
//         },
//         duration: 50 // 每个字符显示间隔（毫秒）
//       });
//       chatStore.updateTokenCount(response.usage);
//     }
//   } catch (error) {
//     // 清理未完成的AI消息
//     chatStore.messages.pop();
//     // ElMessage.error(error.message); // 或移除，由api.js处理
//   } finally {
//     chatStore.isLoading = false;
//   }
// };





// 清除消息
const handleClear = () => {
  chatStore.clearMessages();
};

// 处理消息更新
const handleMessageUpdate = async (updatedMessage) => {
  const index = chatStore.messages.findIndex(m => m.id === updatedMessage.id);
  if (index !== -1) {
    chatStore.messages.splice(index, 2);
    await handleSend(updatedMessage.content);
  }
};

// 删除消息
const handleMessageDelete = (message) => {
  const index = chatStore.messages.findIndex(m => m.id === message.id);
  if (index !== -1) chatStore.messages.splice(index, 2);
};

// 重新生成
const handleRegenerate = async (message) => {
  const index = chatStore.messages.findIndex(m => m.id === message.id && m.role === 'assistant');
  if (index > 0) {
    const userMessage = chatStore.messages[index - 1];
    chatStore.messages.splice(index - 1, 2);
    chatStore.isLoading = true;
    try {
      await handleSend(userMessage.content);
    } catch (error) {
      chatStore.messages.splice(index, 0, message);
    } finally {
      chatStore.isLoading = false;
    }
  }
};


const settingsStore = useSettingsStore()

// 绑定当前选中的模型
const selectedModel = computed({
  get: () => settingsStore.model,
  set: (val) => { settingsStore.model = val },
});

// 保存模型选择
const saveModelSelection = async () => {
  try {
    // 1. 先更新本地模型状态
    settingsStore.model = selectedModel.value;
     // 判断是否为项目管理模型（URL 包含 'project'）
     console.log('进入saveModelSelection',selectedModel.value.type)
    const isProjectModel = selectedModel.value.type === 'project';
    
    // 显式调用 Store 的方法
    settingsStore.toggleProfessionalMode(isProjectModel);

    ElMessage.success({
      message:'模型已切换',
      duration: 1000
    });

    // 新增：切换模型后清空聊天内容
    chatStore.clearMessages();
  } catch (error) {
    ElMessage.error('切换失败，请重试');
    // 回滚到旧模型（可选）
    selectedModel.value = settingsStore.model;
  }
};

// 在ChatView.vue的<script setup>中新增计算属性
const currentButtonColor = computed(() => {
  if (selectedModel.value.type === 'kingsha') {
    return '#003bf4'; // 对应顶部颜色#003bf4
  } else if (selectedModel.value.type === 'project') {
    return '#f4ba40'; // 对应顶部颜色#f4ba40
  } else {
    return '#0132fe'; // 默认颜色（原按钮颜色）
  }
});

const modelColorMap = {
  'https://test_ai.kingsha.com/': '#0132fe', // Kingsha AI 默认颜色
  'https://ai_project.idimage.cn/': '#0066cc', // AI项目管理颜色
  // 其他模型可继续添加
};

</script>

<style lang="scss" scoped>
// iOS Safari 特殊处理
@supports (-webkit-touch-callout: none) {
  .chat-container {
    .messages-container {
      margin-top: calc(60px + env(safe-area-inset-top)); // 导航栏高度60px + 安全区
      height: calc(100vh - 60px - 80px - env(safe-area-inset-bottom)); // 减去底部安全区
    }
  }
}

.model-selector {
  :deep(.el-select) {
    // 移除默认边框和背景
    border: none !important;
    background-color: transparent !important;

    // 处理输入框内部样式
    .el-input__inner {
      // 文字颜色改为白色
      color: white !important;
      // 移除内边距避免文字偏移
      padding: 0 !important;
      // 移除下划线效果
      border-bottom: none !important;
    }

    // 修改下拉箭头颜色
    .el-input__suffix {
      .el-select__caret {
        color: white !important;
      }
    }

    // 处理焦点状态样式
    &:focus {
      .el-input__inner {
        border-color: transparent !important;
        box-shadow: none !important;
      }
    }
  }
}
.model-container {
  :deep(.el-select-dropdown) {
    // 下拉菜单背景保持默认（可选）
    background-color: rgba(255,255,255,0.1) !important; // 半透明背景
  }
}

:deep(.el-select__wrapper) {
  box-shadow: none;
  background: transparent;
}


.chat-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px !important;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: env(safe-area-inset-top) env(safe-area-inset-right) 0 env(safe-area-inset-left) !important;
  background-color: var(--el-color-white);
  border-bottom: 1px solid var(--border-color);
  -webkit-transform: translateZ(0) !important;
  transform: translateZ(0) !important;
}



.model-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.model-selector {
  margin: 0;
  flex-shrink: 0;

  :deep(.el-select) {
    width: 120px !important;
    border: none !important;
    background-color: transparent !important;
    box-shadow: none !important;
  }


  :deep(.el-input__suffix) {
    margin-right: 4px !important; /* 原默认约12px */
    .el-select__caret {
      margin-top: -2px !important; /* 垂直居中调整 */
      color: var(--text-color, #333) !important;
    }
  }
  :deep(.el-select__placeholder) {
    font-weight: bold;    /* 加粗 */
    font-size: 16px;      /* 字号增大 */
    color: var(--text-color, #fff); /* 根据需求调整颜色 */
  }

  :deep(.el-input__inner) {
    padding-right: 20px !important; /* 原默认约20px */
    border: none !important;
    background-color: transparent !important;
    padding: 0 !important;
    &:focus {
      border-color: transparent !important;
      box-shadow: none !important;
    }
  }

  :deep(.el-select__caret) {
    color: var(--text-color, white) !important;
  }

  :deep(.el-select-dropdown) {
    border: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
  }

}

// 移动端特殊处理
// 移动端适配
@media (max-width: 768px) {
  .chat-container {
    .messages-container {
      margin-top: 60px !important;
      padding-top: 0 !important;
    }
  }
}

.mobile-view {
  .chat-header {
    padding-top: max(env(safe-area-inset-top), 0.8rem);
  }

// 消息容器适配
.messages-container {
  flex: 1;
  margin-top: 60px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
  z-index: 1;
  // height: calc(100vh - 60px - env(safe-area-inset-bottom));
  // padding-bottom: 0; // 移除冗余 padding
}
  .el-table {
    font-size: 14px;
  }

  .detail-dialog {
    width: 90vw !important;
    top: 40% !important;
    right: 5vw !important;
    .dialog-content {
      padding: 12px !important;
    }
  }

  // 强制行内元素换行
  .markdown-body {
    :deep() {
      code {
        word-break: break-word !important;
      }
    }
  }
}



.markdown-body {
    :deep() {
      // Markdown 内容样式
      h1, h2, h3, h4, h5, h6 {
        margin: 0.5rem 0;
        font-weight: 600;
        line-height: 1.25;
      }

      p {
        margin: 0.25rem 0;
      }

      code {
        font-family: var(--code-font-family);
        padding: 0.2em 0.4em;
        margin: 0;
        font-size: 85%;
        background-color: var(--code-bg);
        border-radius: 3px;
        color: var(--code-text);
      }

      pre {
        position: relative;
        padding: 2rem 1rem 1rem;
        overflow: auto;
        font-size: 85%;
        line-height: 1.45;
        background-color: var(--code-block-bg);
        border-radius: var(--border-radius);
        margin: 0.5rem 0;
        border: 1px solid var(--border-color);
        
        // 代码头部样式
        .code-header {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          padding: 0.3rem 1rem;
          background-color: var(--code-header-bg);
          border-bottom: 1px solid var(--border-color);
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-family: var(--code-font-family);
          
          .code-lang {
            font-size: 0.8rem;
            color: var(--text-color-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
          }
        }

        &::after {
          content: "点击复制";
          position: absolute;
          top: 0.3rem;
          right: 1rem;
          padding: 0.2rem 0.5rem;
          font-size: 0.75rem;
          color: var(--text-color-secondary);
          opacity: 0;
          transition: opacity 0.3s;
          font-family: system-ui, -apple-system, sans-serif;
        }

        &:hover::after {
          opacity: 0.8;
        }

        code {
          padding: 0;
          background-color: transparent;
          color: inherit;
          display: block;
          font-family: var(--code-font-family);
        }
      }

      blockquote {
        margin: 0.25rem 0;
        padding: 0 0.75rem;
        color: var(--text-color-secondary);
        border-left: 0.25rem solid var(--border-color);
      }

      ul, ol {
        margin: 0.25rem 0;
        padding-left: 1.5rem;
      }

      table {
        border-collapse: collapse;
        width: 100%;
        margin: 0.25rem 0;

        th, td {
          padding: 0.5rem;
          border: 1px solid var(--border-color);
        }

        th {
          background-color: var(--bg-color-secondary);
        }
      }

      img {
        max-width: 100%;
        max-height: 300px;
        object-fit: contain;
        margin: 0.5rem 0;
        border-radius: var(--border-radius);
        cursor: pointer;
        
        &:hover {
          opacity: 0.9;
        }
      }

      a {
        color: var(--primary-color);
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

/* 文件卡片整体布局 */
.file-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 160px;
  padding: 8px 12px;
  margin: 8px 0;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.15);
  cursor: pointer;
  transition: background-color 0.3s;
}

.file-card:hover {
  background-color: #f5f5f5;
}

/* 左侧文件信息部分 */
.file-info {
  display: flex;
  flex-direction: column;
  margin-right: 12px;
}

.file-name {
      font-size: 14px;
      color: #333;
      font-weight: 500;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: calc(10ch); // 10个字符宽度（ch单位根据字体宽度计算）
    }

.file-size {
  font-size: 12px;
  color: #999;
}

/* 右侧图标部分 */
.file-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 32px;
  font-size: 40px;
  color: #4caf50;
}






.download-btn:hover {
  background-color: #218838;
}


      > *:last-child {
        margin-bottom: 0;
      }
    }
  }

.data-table-container {
  .el-table {
    border: 1px solid var(--border-color);
    .data-row {
      cursor: pointer;
      &:hover {
        background-color: var(--gray-bg);
      }
    }
  }
}

.detail-dialog {
  // position: fixed !important;
  // right: 0;
  // top: 50% !important;
  // transform: translateY(-50%);
  // width: 400px;
  // max-height: 80vh;
  // overflow-y: auto;
  // border-radius: 8px;
  // box-shadow: 0 2px 8px rgba(0,0,0,0.15);

  position: fixed !important;
  top: 50% !important;
  left: 5% !important; /* 避免右侧边缘被截断 */
  right: auto !important;
  width: 90% !important;

  .dialog-content {
    padding: 16px;
    pre {
      white-space: pre-wrap;
      background-color: var(--code-bg);
      padding: 1rem;
      border-radius: 4px;
      overflow-x: auto;
    }
  }

  .dialog-footer {
    text-align: right;
    padding: 12px;
  }
}
.chat-container {
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
}


.chat-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  -webkit-overflow-scrolling: touch;
}


.messages-container {
  flex: 1;
  margin-top: 60px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
  z-index: 1;
  padding-bottom: 80px; // 默认输入框高度 + 一些间距
  height: calc(100vh - 60px - 80px);
}

.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}


.header-actions {
  display: flex;
  gap: 1rem;
}

.data-popover {
  padding: 16px;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
}
</style>
